package com.edu.labmanager.service.impl;

import com.edu.labmanager.common.MyUserDetails;
import com.edu.labmanager.entity.User;
import com.edu.labmanager.mapper.UserMapper;
import com.edu.labmanager.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 用户表，存储系统用户的登录信息和角色权限 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = query().eq("user_name", username).one();
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        ArrayList<String> authorities = new ArrayList<>();
        authorities.add(user.getRole());

        System.out.println("用户" + user.getUserName() + "的权限：" + authorities);
        //自定义myUserDetails，新增字段id
       return new MyUserDetails(user.getUserName(), user.getPassword(),Long.valueOf(user.getUserId()),  AuthorityUtils.createAuthorityList(authorities));
    }
}
